package com.fnzx.controller;

import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fnzx.entity.DemandEntity;
import com.fnzx.entity.EnterpriseUserEntity;
import com.fnzx.entity.ProjectEntity;
import com.fnzx.entity.RelationEntity;
import com.fnzx.entity.vo.DemandVo;
import com.fnzx.service.DemandService;
import com.fnzx.service.EnterpriseUserService;
import com.fnzx.service.ProjectService;
import com.fnzx.service.RelationService;
import com.fnzx.util.PageUtils;
import com.fnzx.util.R;
import com.fnzx.util.oss.OssUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.*;
import java.util.*;

@RestController
@RequestMapping("iot/demand")
@Api(tags ="需求模块")
public class DemandController {
    @Autowired
    private DemandService demandService;

    @Autowired
    private ProjectService projectService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private EnterpriseUserService enterpriseUserService;
    /**
     * 列表
     */
    @ApiOperation(value = "获取所有需求",notes="查询出所有需求(page->当前页面,limit->每页记录数)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "limit",value = "每页记录数",paramType = "query",required = true,dataType = "String")

    })
    @GetMapping("/list")
    public R list(@ApiIgnore @RequestParam Map<String,Object> params){
        PageUtils page = demandService.queryPage(params);
        return R.ok().put("page",page);
    }

    /**
     * 信息
     */
    @ApiOperation(value = "后台页面-id查询",notes = "通过需求id查询")
    @GetMapping("/info/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "需求id",paramType = "path",required = true,dataType = "String"),
    })
    public R info(@PathVariable("id") Long id){
        DemandEntity demand = demandService.getById(id);
        ProjectEntity project = projectService.getOne(new QueryWrapper<ProjectEntity>().eq("demand_id", id));
        RelationEntity relation = relationService.getOne(new QueryWrapper<RelationEntity>().eq("id", demand.getCategoryId()));
        EnterpriseUserEntity one = enterpriseUserService.getOne(new QueryWrapper<EnterpriseUserEntity>().eq("id", demand.getEnterpriseId()));
        DemandVo demandVo = new DemandVo(demand, project,relation,one);
        return R.ok().put("demandVo", demandVo);
    }
    /**
     * 获取企业用户需求
     */
    @ApiOperation(value = "企业用户enterprise_id查询",notes = "通过企业用户id查询")
    @GetMapping("/userDemand")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "企业用户id",paramType = "path",required = true,dataType = "String"),
            @ApiImplicitParam(name = "page",value = "当前页",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "limit",value = "每页记录数",paramType = "query",required = true,dataType = "String")
    })
    public R userDemand(@ApiIgnore @RequestParam Map<String,Object> params){
        PageUtils pageUtils = demandService.queryPageByUser(params);
        return R.ok().put("page",pageUtils);
    }
    /**
     * 查询
     */
    @ApiOperation(value = "七个条件查询",notes = "状态 日期 需求名称 需求描述 所属企业 需求分类 项目名称")
    @GetMapping("/info")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status",value = "状态",paramType = "path",required = false,dataType = "String"),
            @ApiImplicitParam(name = "date",value = "日期",paramType = "path",required = false,dataType ="Date"),
            @ApiImplicitParam(name = "name",value = "名称",paramType = "path",required = false,dataType = "String"),
            @ApiImplicitParam(name = "describes",value = "描述",paramType = "path",required = false,dataType = "String"),
            @ApiImplicitParam(name = "enter_name",value = "企业用户名称",paramType = "path",required = false,dataType = "String"),
            @ApiImplicitParam(name = "category",value = "需求分类",paramType = "path",required = false,dataType = "String"),
            @ApiImplicitParam(name = "pro_name",value = "项目名称",paramType = "path",required = false,dataType = "String"),
                    })
    public R selectBy(String status, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date,
                      String name,String describes,String enter_name, String category,String pro_name){
        List<DemandVo> vo =new ArrayList<>();

        QueryWrapper<DemandEntity> demandEntity =new QueryWrapper<>();

                if("未处理".equals(status)){
                    demandEntity.eq("status",0);
                }else if("处理中".equals(status)){
                    demandEntity.eq("status",1);
                }else if("处理完成".equals(status)){
                    demandEntity.eq("status",2);
                }else if("需求关闭".equals(status)){
                    demandEntity.eq("status",4);
                }


        if(date!=null ){
            Date d =date;
            demandEntity.orderByDesc("gmt_created").between("gmt_created",date,new Date(d.getTime()+1*24*60*60*1000));
        }
        if(name==null || name.isEmpty()){}else {
            demandEntity.like("demand_name", name);
        }
        if(describes==null || describes.isEmpty()){}else {
            demandEntity.like("demand_describe", describes);
        }
        if(enter_name==null || enter_name.isEmpty()){

        }else{
            List<Long> en_ids=new ArrayList<>();
            QueryWrapper<EnterpriseUserEntity> enterpriseUserEntity = new QueryWrapper<>();
            enterpriseUserEntity.eq("enterprise_name",enter_name);
            List<EnterpriseUserEntity> entities = enterpriseUserService.list(enterpriseUserEntity);
            for (EnterpriseUserEntity enter :entities){
                en_ids.add(enter.getId());
            }
            demandEntity.in("enterprise_id",en_ids);
        }

        if(category==null || category.isEmpty()){

        }else{
            List<Long> ca_ids=new ArrayList<>();
            QueryWrapper<RelationEntity> relation =new QueryWrapper<>();
            relation.eq("value",category);
            List<RelationEntity> list = relationService.list(relation);
            for(RelationEntity rela:list){
                ca_ids.add(rela.getId());
            }
            demandEntity.in("category_id",ca_ids);
        }
        if(pro_name==null || pro_name.isEmpty()){

        }else{
            List<Long> de_ids=new ArrayList<>();
            QueryWrapper<ProjectEntity> project =new QueryWrapper<>();
            project.like("project_name",pro_name);
            List<ProjectEntity> pros=projectService.list(project);
            for(ProjectEntity pro:pros){
                de_ids.add(pro.getDemandId());
            }
            demandEntity.in("id",de_ids);
        }
        List<DemandEntity> list = demandService.list(demandEntity);

        for(DemandEntity demand:list){
            ProjectEntity project = projectService.getOne(new QueryWrapper<ProjectEntity>().eq("demand_id", demand.getId()));
            RelationEntity relation = relationService.getOne(new QueryWrapper<RelationEntity>().eq("id", demand.getCategoryId()));
            EnterpriseUserEntity one = enterpriseUserService.getOne(new QueryWrapper<EnterpriseUserEntity>().eq("id", demand.getEnterpriseId()));
            DemandVo demandVo = new DemandVo(demand, project,relation,one);

           vo.add(demandVo);
        }

            return R.ok().put("demandVo", vo);

    }


    /**
     * 保存
     */
    @ApiOperation(value = "后台页面-添加需求", notes = "添加需求{\"demandName\":,\"demandDescribe\":,\"categoryId\":,\"remarks\";,\"docFilesUrl\":}")
    @PostMapping("/save")
    public R save(@RequestBody DemandEntity demand){
        demand.setStatus(0);
        demandService.save(demand);
        return R.ok();
    }

    /**
     * 修改需求
     */
    @ApiOperation(value = "后台页面-修改需求", notes = "修改需求{\"id\":,\"demandName\":,\"demandDescribe\":,\"categoryId\":,\"remarks\":,\"docFilesUrl\":}")
    @PostMapping("/update")
    public R update(@RequestBody DemandEntity demand){
        demandService.updateById(demand);
        return R.ok();
    }
    /**
     * 修改需求状态
     */
    @ApiOperation(value = "修改需求状态", notes = "修改需求状态{\"id\":,\"status\":  处理中  处理关闭  需求关闭}")
    @PostMapping("/updateStatus")
    public R updateStatus(@RequestParam("id") Long demandId,@RequestParam("status") String status){
        DemandEntity demand = demandService.getById(demandId);
        if(status.equals("处理中")){
            demand.setStatus(1);
        }else if(status.equals("处理完成")){
            demand.setStatus(2);
        }else if(status.equals("需求关闭")){
            demand.setStatus(3);
        }else{
            demand.setStatus(0);
        }
        demandService.updateById(demand);
        return R.ok();
    }

    /**
     * 删除
     */
    @ApiOperation(value = "后台页面-删除", notes = "删除需求,可多个")
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids,
            @RequestHeader String token){
        if(ids.length !=0 && ids !=null){
            demandService.removeByIds(Arrays.asList(ids));

            for (int i=0;i<ids.length;i++){
                Long id = ids[i];
                ProjectEntity project = projectService.getOne(new QueryWrapper<ProjectEntity>().eq("demand_id", id));
                Long projectId = project.getId();
                projectService.removeByIds(Arrays.asList(projectId));
            }

            return R.ok();
        }
        return R.ok("id不能为空");
    }
    /**
     * 上传附件
     */
    @ApiOperation(value = "上传附件", notes = "上传文件到阿里云oss")
    @PostMapping("/fileUpload")
    public R fileUpload(MultipartFile file) throws IOException {
        //获取上传文件
        String url = OssUtils.upload(file);
        return R.ok(url);
    }

//    /**
//     * 下载附件
//     */
//    @ApiOperation(value = "下载需求文档",notes = "通过需求id查下载需求文档")
//    @PostMapping("/download")
//    public R fileDownload(@RequestParam("id") Long demandId,
//                          @RequestParam("localPath") String localPath,
//                          @RequestParam("saveName") String saveName){
//        DemandEntity demand = demandService.getById(demandId);
//        String url = demand.getDocFilesUrl();
//
//      //  String localPath="D:\\Downloads\\";
//       // String saveName="1.doc";
//        OssUtils.down(url,localPath,saveName);
//
//        return R.ok();
//    }
    /**
     * 获取需求分类
     */
    @ApiOperation(value = "获取所有需求分类",notes="获取到需求分类")
    @GetMapping("/getFen")
    public R getFen(){
        List<RelationEntity> fen = demandService.getFen();
        return R.ok().put("category",fen);
    }
}
